package com.appointment.controller;

import com.appointment.annotation.RoleRequired;
import com.appointment.dto.*;
import com.appointment.pojo.Professor;
import com.appointment.pojo.User;
import com.appointment.result.R;
import com.appointment.service.ProfessorService;
import com.appointment.service.UserService;
import com.appointment.utils.CodeUtils;
import com.appointment.utils.Jwt.JwtRoles;
import com.appointment.utils.Jwt.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private ProfessorService professorService;

    @Autowired
    private JwtUtil jwtUtil;

    // 验证码过期时间
    private static final long SMS_EXPIRE_TIME = 60 * 5;

    @PostMapping("/user/getSmsCode")
    public R<Object> getSmsCode(@Valid @RequestBody SmsCodeRequestDto smsCodeRequestDto) {
        // 获取手机号
        String phone = smsCodeRequestDto.getPhone();
        // 生成验证码
        String code = CodeUtils.generateValidateCode();
        // 存入redis，设置过期时间
        redisTemplate.opsForValue().set(phone, code, SMS_EXPIRE_TIME, TimeUnit.SECONDS);
        Map<String, String> response = new HashMap<>();
        response.put("code", code);
        return R.success(response);
    }

    @PostMapping("/user/login")
    public R<Object> login(@Valid @RequestBody UserLoginRequestDto userLoginRequestDto) {
        // 获取用户名，手机号，验证码
        String name = userLoginRequestDto.getName();
        String phone = userLoginRequestDto.getPhone();
        String code = userLoginRequestDto.getCode();
        // 验证验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            return R.error("验证码错误");
        }
        // 清除验证码
        redisTemplate.delete(phone);
        // 验证通过，查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        // 判断用户是否存在，不存在则创建
        if (user == null) {
            user = new User();
            user.setName(name);
            user.setPhone(phone);
            userService.save(user);
        } else {
            // 用户存在，检查用户名是否匹配
            if (!user.getName().equals(name)) {
                return R.error("用户名与手机号不匹配");
            }
        }
        // 生成token
        String userId = user.getId();
        String token = jwtUtil.generateToken(userId, JwtRoles.USER);
        // 创建DTO返回
        UserAuthDto userAuthDto = new UserAuthDto();
        userAuthDto.setUserInfo(user);
        userAuthDto.setToken(token);
        return R.success(userAuthDto);
    }

    @RoleRequired(JwtRoles.USER)
    @PostMapping("/user/logout")
    public R<Object> logout(HttpServletRequest request) {
        // 获取token
        String token = (String) request.getAttribute("token");
        if (token == null) {
            return R.error("token不能为空");
        }
        // 添加到黑名单
        boolean flag = jwtUtil.addBlackList(token);
        return flag ? R.success("退出登录成功") : R.error("退出登录失败");
    }

    @RoleRequired(JwtRoles.PROFESSOR)
    @PostMapping("/user/confirm")
    public R<Object> confirm(@Valid @RequestBody ProfessorConfirmRequestDto professorConfirmRequestDto) {
        String phone = professorConfirmRequestDto.getPhone();
        // 查询用户
        LambdaQueryWrapper<Professor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Professor::getPhone, phone);
        queryWrapper.select(Professor::getId, Professor::getName, Professor::getAvatarUrl);
        Professor professor = professorService.getOne(queryWrapper);
        if (professor == null) {
            return R.error("用户不存在");
        }
        // 生成token
        String professorId = professor.getId();
        String token = jwtUtil.generateToken(professorId, JwtRoles.PROFESSOR);
        // 创建DTO返回
        ProfessorAuthDto professorAuthDto = new ProfessorAuthDto();
        professorAuthDto.setToken(token);
        ProfessorDto professorDto = new ProfessorDto();
        BeanUtils.copyProperties(professor, professorDto);
        professorAuthDto.setProfessorInfo(professorDto);
        return R.success(professorAuthDto);
    }

}
